package commons.base.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

/**
 * 封装了事务操作
 * @author Administrator
 *
 */
public class TransactionOp {

	private Connection conn;
	private int level;
	private QueryRunner qr;
	
	public TransactionOp(QueryRunner qr) throws SQLException{
		this.qr = qr;
		this.conn = qr.getDataSource().getConnection();
		
		level = conn.getTransactionIsolation();
		conn.setAutoCommit(false);
		conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
	}
	
	/**
	 * 结束事务
	 * @throws SQLException
	 */
	public void endTransaction() throws SQLException{
		if(conn != null){
			try {
				conn.setTransactionIsolation(level);
				conn.setAutoCommit(true);
			} finally {
				conn.close();
			}
		}
	}
	
	public void commit() throws SQLException{
		if(conn != null){
			conn.commit();
		}
	}
	
	public void rollback() throws SQLException{
		if(conn != null){
			conn.rollback();
		}
	}
	
	public List<Map<String, Object>> query(String sql, Object...params) throws SQLException{
		return qr.query(conn, sql, new MapListHandler(), params);
	}
	
	public <T> List<T> query(String sql, Class<T> clazz, Object...params) throws SQLException{
		return qr.query(conn, sql, new BeanListHandler<T>(clazz), params);
	}
	
	public Map<String, Object> queryFirst(String sql, Object...params) throws SQLException{
		return qr.query(conn, sql, new MapHandler(), params);
	}
	
	public <T> T queryFirst(String sql, Class<T> clazz, Object...params) throws SQLException{
		return qr.query(conn, sql, new BeanHandler<T>(clazz), params);
	}
	
	public <T> T queryUnique(String sql, Object...params) throws SQLException{
		return qr.query(conn, sql, new ScalarHandler<T>(), params);
	}
	
	public int update(String sql, Object...params) throws SQLException{
		return qr.update(conn, sql, params);
	}
}
